package com.ggb.reactive.utils
import com.ggb.reactive.extension.log
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Mono

object HttpClientUtil {

    private val webClient: WebClient = WebClient.builder().build()
    private val tempMap: Map<String, String> = emptyMap()

    //fun doGet(url: String, paramMap: Map<String, String>?): Mono<String> {
    //    return webClient.get()
    //        .uri { uriBuilder ->
    //            uriBuilder.path(url)
    //            if (paramMap != null) {
    //                for ((key, value) in paramMap) {
    //                    uriBuilder.queryParam(key, value)
    //                }
    //            }
    //            uriBuilder.build()
    //        }
    //        .retrieve()
    //        .bodyToMono(String::class.java)
    //}
    fun doGet(url: String, paramMap: Map<String, String>?): Mono<String> {
        val uri = UriComponentsBuilder.fromHttpUrl(url).apply {
            paramMap?.forEach { (key, value) ->
                queryParam(key, value)
            }
        }.build().toUri()
        log.info("uri: {}", uri)
        return webClient.get()
            .uri(uri)
            .retrieve()
            .bodyToMono(String::class.java)
    }


    fun doPost(url: String, paramMap: Map<String, String>?): Mono<String> {
        return webClient.post()
            .uri(url)
            .bodyValue(paramMap ?: tempMap)
            .retrieve()
            .bodyToMono(String::class.java)
    }

    fun doPost4Json(url: String, jsonMap: Map<String, Any>?): Mono<String> {
        return webClient.post()
            .uri(url)
            .bodyValue(jsonMap ?: emptyMap<String, Any>())
            .retrieve()
            .bodyToMono(String::class.java)
    }
}